package juc;

import com.beust.jcommander.internal.Lists;
import org.junit.Test;

import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class CyclicBarrierTest {

	private final AtomicInteger poolNumber = new AtomicInteger(1);

	/**
	 * 定义一个线程池
	 */
	private ThreadPoolExecutor executor = new ThreadPoolExecutor(50, 50, 60, TimeUnit.SECONDS,
			new LinkedBlockingDeque<>(2000), r -> new Thread(r, "工人" + poolNumber.incrementAndGet()));

	class Worker implements Runnable {

		private CyclicBarrier cyclicBarrier;

		Worker(CyclicBarrier cyclicBarrier) {
			this.cyclicBarrier = cyclicBarrier;
		}

		@Override
		public void run() {
			try {
				Thread.sleep(new Random().nextInt(10000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "执行任务结束");
			try {
				cyclicBarrier.await();
			} catch (InterruptedException | BrokenBarrierException e) {
				e.printStackTrace();
			}
		}
	}

	@Test
	public void testCountDownLatch() {
		CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> System.out.println("一轮结束,执行barrierCommand"));
		List<FutureTask> futureTaskList = Lists.newArrayList();
		for (int i = 0; i < 10; i++) {
			futureTaskList.add((FutureTask) executor.submit(new Worker(cyclicBarrier)));
		}
		for (FutureTask futureTask : futureTaskList) {
			try {
				futureTask.get();
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
		}
	}
}
